<?php

  function userLogin($user_name, $password) {
    $return_string = "";
    if (isset($_SESSION['user_name']) && isset($_SESSION['user_id'])) {
      if ($_SESSION['user_name'] == $user_name) {
        $return_string .= "<returncode>1</returncode>\n";
        $return_string .= "<username>" . $user_name . "</username>\n";
      } else {
        $return_string .= "<returncode>0</returncode>\n";
        $return_string .= "<errormessage>Another user is still logged in.</errormessage>\n";
      }
    } else {
      $query = "SELECT id,password FROM User WHERE name = '" . $user_name . "'";
      $result = mysql_query($query);
      
      if (mysql_num_rows($result) == 0) {
        $return_string .= "<returncode>0</returncode>\n";
        $return_string .= "<errormessage>Wrong user name or password!</errormessage>\n";
      } else {
        $encrypted_pass = sha1($password);
        $result_row = mysql_fetch_assoc($result);
        $user_id = $result_row['id'];
        if ($encrypted_pass == $result_row['password']) {
          $return_string .= "<returncode>1</returncode>\n";
          $return_string .= "<username>" . $user_name . "</username>\n";
          $_SESSION['user_name'] = $user_name;
          $_SESSION['user_id'] = $user_id;
        } else {
          $return_string .= "<returncode>0</returncode>\n";
          $return_string .= "<errormessage>Wrong user name or password!</errormessage>\n";
        }
      }
    }
    return $return_string;
  }
?>
